﻿package net.wangit.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;

public class DateUtil {

	private static final DateFormat DATE_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd");
	private static final DateFormat TIME_FORMAT = new SimpleDateFormat(
			"HH:mm:ss");
	private static final DateFormat DATETIME_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private static final DateFormat TIMESTAMP_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss.SSS");

	public DateUtil() {
	}

	public static DateFormat getDateFormat() {
		return DATE_FORMAT;
	}

	public static DateFormat getTimeFormat() {
		return TIME_FORMAT;
	}

	public static DateFormat getDatetimeFormat() {
		return DATETIME_FORMAT;
	}

	public static DateFormat getTimestampFormat() {
		return TIMESTAMP_FORMAT;
	}

	public static String addDateByDay(String date, int day) {
		if (!Checker.isDate(date)) {
			return null;
		} else {
			Date date1 = getDate(date);
			GregorianCalendar calendar = new GregorianCalendar();
			calendar.setTime(date1);
			calendar.add(6, day);
			return getDate(calendar.getTime());
		}
	}

	public static String addDatetimeByDay(String datetime, int days) {
		if (!Checker.isTimestamp(datetime) && !Checker.isDate(datetime))
			return null;
		if (Checker.isDate(datetime))
			datetime = (new StringBuilder(String.valueOf(datetime))).append(
					" 00:00:00.000").toString();
		Date date1 = getDate(datetime);
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(date1);
		calendar.add(6, days);
		return getTimestamp(calendar.getTime());
	}

	public static String addDatetimeByMonth(String datetime, int months) {
		if (!Checker.isTimestamp(datetime) && !Checker.isDate(datetime))
			return null;
		if (Checker.isDate(datetime) && !Checker.isTimestamp(datetime))
			datetime = (new StringBuilder(String.valueOf(datetime))).append(
					" 00:00:00.000").toString();
		Date date1 = getDate(datetime);
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(date1);
		calendar.add(2, months);
		return getTimestamp(calendar.getTime());
	}

	public static String addDatetimeBySecond(String datetime, int seconds) {
		if (!Checker.isTimestamp(datetime) && !Checker.isDate(datetime))
			return null;
		if (Checker.isDate(datetime))
			datetime = (new StringBuilder(String.valueOf(datetime))).append(
					" 00:00:00.000").toString();
		Date date1 = getDate(datetime);
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(date1);
		calendar.add(13, seconds);
		return getTimestamp(calendar.getTime());
	}

	public static String getCurrentDate() {
		return getDate(new Date());
	}

	public static String getFirstDateOfMonth() {
		String date = getDate(new Date());
		return (new StringBuilder(String.valueOf(date.substring(0, 8))))
				.append("01").toString();
	}

	public static String getDate(Date date) {
		return DATE_FORMAT.format(date);
	}

	public static Date getDate(String dateStr) {
		try {
			if (Checker.isTimestamp(dateStr)) {
				if (dateStr.indexOf(".") < 0)
					dateStr = (new StringBuilder(String.valueOf(dateStr)))
							.append(".000").toString();
				return TIMESTAMP_FORMAT.parse(dateStr);
			} else if (Checker.isDate(dateStr)) {
				return DATE_FORMAT.parse(dateStr);
			} else if (Checker.isTime(dateStr)) {
				return TIME_FORMAT.parse(dateStr);
			}
		} catch (Exception ex) {
		}
		return null;
	}

	public static String getCurrentDatetime() {
		return getTimestamp(new Date());
	}

	public static String getCurrentTime() {
		return getTime(new Date());
	}

	public static String getTime(Date date) {
		return TIME_FORMAT.format(date);
	}

	public static String getDatetime(Date date) {
		return DATETIME_FORMAT.format(date);
	}

	public static String getTimestamp(Date date) {
		return TIMESTAMP_FORMAT.format(date);
	}

	private static String getFormatDatetime(String datetime) {
		if (Checker.isTimestamp(datetime))
			return datetime;
		try {
			StringBuffer retStr;
			StringTokenizer st;
			retStr = new StringBuffer();
			st = new StringTokenizer(datetime.trim());
			retStr.append(st.nextToken());
			if (retStr.substring(6, 7).equals("-"))
				retStr = retStr.insert(5, "0");
			if (retStr.length() < 10)
				retStr = retStr.insert(8, "0");
			if (st.countTokens() < 1)
				return retStr.append(" 00:00:00.000").toString();
			String s = new String();
			s = st.nextToken();
			st = new StringTokenizer(s, ":");
			int count = st.countTokens();
			if (count == 1)
				retStr.append(" ").append(s).append(":00:00.000");
			if (count == 2)
				retStr.append(" ").append(s).append(":00.000");
			if (count == 3)
				retStr.append(" ").append(s);
			return retStr.toString();
		} catch (Exception e) {
			return null;
		}
	}

	public static int getMonth(String datetime) {
		String s = getFormatDatetime(datetime);
		if (!Checker.isTimestamp(s))
			return 0;
		else
			return Integer.parseInt(s.substring(5, 7));
	}

	public static int getYear(String datetime) {
		String s = getFormatDatetime(datetime);
		if (!Checker.isTimestamp(s))
			return 0;
		else
			return Integer.parseInt(s.substring(0, 4));
	}

	public static int getDay(String datetime) {
		String s = getFormatDatetime(datetime);
		if (!Checker.isTimestamp(s))
			return 0;
		else
			return Integer.parseInt(s.substring(8, 10));
	}

	public static int getHour(String datetime) {
		String s = getFormatDatetime(datetime);
		if (!Checker.isTimestamp(s))
			return 0;
		else
			return Integer.parseInt(s.substring(11, 13));
	}

	public static int getMinute(String datetime) {
		String s = getFormatDatetime(datetime);
		if (!Checker.isTimestamp(s))
			return 0;
		else
			return Integer.parseInt(s.substring(14, 16));
	}

	public static int getSecond(String datetime) {
		String s = getFormatDatetime(datetime);
		if (!Checker.isTimestamp(s))
			return 0;
		else
			return Integer.parseInt(s.substring(17, 19));
	}

	public static String get400Datetime(String datetime) {
		StringBuffer s = new StringBuffer(getFormatDatetime(datetime));
		return s.replace(10, 11, "-").replace(13, 14, ".").replace(16, 17, ".")
				.toString();
	}

	public static String getFormatDateStr(String datetime, int Type) {
		if (Checker.isEmpty(datetime))
			return "";
		datetime = datetime.trim();
		StringBuffer dtStr = new StringBuffer();
		if (datetime.indexOf(".") > 0)
			datetime = datetime.substring(0, datetime.indexOf("."));
		int dtArry[] = new int[6];
		dtArry[0] = Integer.parseInt(datetime.substring(0, 4));
		dtArry[1] = Integer.parseInt(datetime.substring(5, 7));
		dtArry[2] = Integer.parseInt(datetime.substring(8, 10));
		dtArry[3] = Integer.parseInt(datetime.substring(11, 13));
		dtArry[4] = Integer.parseInt(datetime.substring(14, 16));
		dtArry[5] = Integer.parseInt(datetime.substring(17));
		switch (Type) {
		case 1: // '\001'
			return dtStr.append(dtArry[0]).append("年").append(dtArry[1])
					.append("月").append(dtArry[2]).append("日").toString();

		case 2: // '\002'
			return dtStr.append(dtArry[3]).append("时").append(dtArry[4])
					.append("分").append(dtArry[5]).append("秒").toString();

		case 3: // '\003'
			return dtStr.append(dtArry[0]).append("年").append(dtArry[1])
					.append("月").append(dtArry[2]).append("日").append(" ")
					.append(dtArry[3]).append("时").append(dtArry[4])
					.append("分").append(dtArry[5]).append("秒").toString();

		case 4: // '\004'
			return dtStr.append(dtArry[1]).append("/").append(dtArry[2])
					.append(" ").append(dtArry[3]).append(":")
					.append(dtArry[4]).toString();

		case 5: // '\005'
			return dtStr.append(dtArry[2]).append("日").append(dtArry[3])
					.append(":").append(dtArry[4]).toString();
		}
		return datetime;
	}

	public static boolean isLeapYear(int year) {
		if (year % 400 == 0)
			return true;
		return year % 4 == 0 && year % 100 != 0;
	}

	public static boolean isLeapYear(String year) {
		if (!Checker.isInteger(year))
			return false;
		else
			return isLeapYear(Integer.parseInt(year));
	}

	public static String getLastDateOfMonth(String year, String month) {
		StringBuffer temp = new StringBuffer(year);
		temp.append("-").append(month).append("-");
		if (year.length() != 4 || month.length() > 2) {
			return "";
		} else {
			int y = Integer.parseInt(year);
			int m = Integer.parseInt(month);
			GregorianCalendar gc = new GregorianCalendar(y, --m, 1, 0, 0, 0);
			long first = gc.getTimeInMillis();
			gc.set(y, ++m, 1, 0, 0, 0);
			long second = gc.getTimeInMillis();
			return temp.append((second - first) / 0x5265c00L).toString();
		}
	}

	public static long getGapByDate(String date1, String date2) {
		return getGapByMillisecond(date1, date2) / 0x5265c00L;
	}

	public static long getGapBySecond(String date1, String date2) {
		return getGapByMillisecond(date1, date2) / 1000L;
	}

	public static long getGapByMillisecond(String date1, String date2) {
		return getDate(date2).getTime() - getDate(date1).getTime();
	}

}
